/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client.network;

import java.io.*;
import java.net.*;
import com.cse.p2p.common.*;
import com.cse.p2p.database.*;
import com.cse.p2p.hash.*;
import com.cse.p2p.localfile.*;
import com.cse.p2p.parser.*;
import com.sun.org.apache.bcel.internal.generic.LADD;
import java.util.HashMap;
import java.util.List;

/**
 * 
 * @author TuyetNgan
 */
public class ClientControlTask_Server extends Thread {

	private BufferedReader inStream = null;
	private PrintStream outStream = null;
	private String fromServer, fromClient, fromScreen;
	private BufferedReader infromScreen = null;
	private Socket clientSocket = null;
	private boolean debug = true;

	public ClientControlTask_Server(Socket s) {
		this.clientSocket = s;
		System.out.println( "Accept from "+s.getRemoteSocketAddress());
	}

	private long startTime, endTime;

	public void newChat() {
		try {
			outStream = new PrintStream(new DataOutputStream(
					clientSocket.getOutputStream()));
			inStream = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
			infromScreen = new BufferedReader(new InputStreamReader(System.in));
		} catch (IOException e) {
		}
	}

	public void closeConnection() {
		try {
			outStream.close();
			inStream.close();
			clientSocket.close();
		} catch (IOException e) {
		}

	}

	@Override
	public void run() {
		newChat();
		try {
			/* waiting for server */
			String mess;
			Message message;
			String data;
			boolean flagbreak = false;
			mess = inStream.readLine();
			System.out.println(mess);
			message = Message.fromString(mess);
			int typeOfProtocol = message.getType();
			data = message.getData();

			switch (typeOfProtocol) {
				// Client -> one Peer: ask for one piece of a file
				case Message.MsgType.REQ_ASK_A_PIECE: {
	
					PieceInfo pieceInfo = PieceInfo.fromString(data);
					int pieceID = pieceInfo.getPieceID();
					int fileID = pieceInfo.getFileID();
					if (ClientDatabase.checkPieceExist(pieceID, fileID)) {
						Message messSend = new Message("PUT", "PIECE", "OK");
						outStream.println(messSend.toString());
                        
                        String IPsender = this.clientSocket.getRemoteSocketAddress()
										.toString();
                        
						Thread send = new ClientSendDataTask(
								ClientDatabase.getFilePath(pieceID), fileID,
								pieceID, IPsender.substring(1,IPsender.lastIndexOf(":")),
								CommonSettings.CLIENT_DATA_SERVERSOCKET);
						send.start();
						while (send.isAlive())
							;
						// send finished
					} else {
						Message messSend = new Message("PUT", "PIECE", "NONE");
						outStream.println(messSend.toString());
					}
					break;
				}
				// Server -> one Peer: the info of all available pieces of a file
				case Message.MsgType.REQ_VRF_ALL_PIECES: {
					System.out.println("Server require one peer");
					int fileID = Integer.parseInt(data);
					/* search in DB to get pieces info */
					//ClientDatabase.openDatabase();
					List piecesList = ClientDatabase.getPiecesExist(fileID);
					//ClientDatabase.closeDatabase();
					/* convert List to int[] */
					int[] pieces = new int[piecesList.size()];
					for (int i = 0; i < piecesList.size(); i++) {
						pieces[i] = (Integer) piecesList.get(i);
					}
	
					/* return <peerInfo> to server */
                    String IP = this.clientSocket.getLocalAddress().toString();
					PeerInfo info = new PeerInfo(fileID, pieces, 
							IP.substring(1));
					String peerInfo = info.toString();
                    System.out.println(info.getFileID() + " , " + info.getIP() + " , " + info.getPieces()[0]);
					outStream.println(new Message(Message.Command.PUT,Message.Keyword.VERIFY,peerInfo.toString()));
					
					
					break;
				}
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}
}
